package com.fcat.common.monitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.fcat.base.server.model.DockerInfo;
import com.fcat.base.server.model.Server;
import com.fcat.base.server.model.SysFile;
import com.fcat.base.server.util.ShellCommand;
import com.fcat.common.monitor.service.DictService;
import com.fcat.springboot.mail.service.MailService;
import com.fcat.springboot.mybatis.util.JsonUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("mail")
public class EmailController {
    private static final Logger logger = LoggerFactory.getLogger(EmailController.class);

    @Autowired
    private MailService mailService;
    @Autowired
    private DictService dictService;

    @Value("${spring.mail.username}")
    private String from;

    @Scheduled(cron = "0 0 0/1 * * ? ")
    @ApiOperation(value = "", notes = "")
    @RequestMapping(value = "/sendContent", method = RequestMethod.GET)
    public JSONObject sendContent() {
        String sendToStr = dictService.getListByTypeCode("sendTo").get(0).getValue();
        String[] sendTo = sendToStr.split(",");
        ShellCommand shellCommand = ShellCommand.shellCommandByMeter178();
        Server server = shellCommand.dealServer();
        try {

            String subject ="电表服务器：一小时定时检查";
            String content = server.getName()+"IP: "+server.getIp() +"\n"+
                    "内存使用率："+server.getMem().getUsedRate() +"%"+"\n"+
                    "CPU使用率："+server.getCpu().getUsedRate() +"%"+"\n"+
            "磁盘：\n";
            for(int i=0;i<server.getSysFiles().size();i++){
                SysFile sysFile = server.getSysFiles().get(i);
                content +=sysFile.getFilesystem()+"\t总共："+sysFile.getBlocks()+"MiB\t使用率："+sysFile.getUseRate() +"%"+"\n";
            }
            content += String.format("%-22s%10s%10s\n","容器名称","CPU使用率","内存使用率");
            for(int i=0;i<server.getDockerInfos().size();i++){
                DockerInfo dockerInfo = server.getDockerInfos().get(i);
                content += String.format("%-22s%10s%10s\n",dockerInfo.getName(),dockerInfo.getCpuUseRate(),dockerInfo.getMemUseRate());
            }
            mailService.sendEmail(from,sendTo,subject,content);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonUtil.getSuccessJsonObject();
    }
}